<template>
  <div>
    <div>UV动画</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const width = 800;
    const height = 500;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(-100, 300, 300);
    camera.lookAt(scene.position);
    const render = new THREE.WebGLRenderer();
    render.setSize(width, height);
    console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    const geometry = new THREE.PlaneGeometry(300, 200);

    //纹理贴图加载器TextureLoader
    const texLoader = new THREE.TextureLoader();
    // .load()方法加载图像，返回一个纹理对象Texture
    const texture = texLoader.load('/public/38.png');
    //   texture.offset.x = 0.1;
    // 设置阵列模式
    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    console.log('texture', texture);

    const material = new THREE.MeshLambertMaterial({
      // color: 0xfff123,
      // 设置纹理贴图：Texture对象作为材质map属性的属性值
      map: texture, //map表示材质的颜色贴图属性
      side: THREE.DoubleSide,
      transparent: true, //使用背景透明的png贴图，注意开启透明计算
    });
    const mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    function renderFun() {
      texture.offset.x += 0.001; //设置纹理动画：偏移量根据纹理和动画需要，设置合适的值
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();
  }
</script>
